package com.wy.controller;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wy.common.util.excel.ExcelUtils;
import com.wy.entity.ExcelImportEntity;
import com.wy.entity.KEntity;
import com.wy.entity.KParam;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class ExcelController {
    @PostMapping("/uploadFile")
    public void uploadFile(@RequestPart("multipartFile") MultipartFile multipartFile) throws Exception {
        Map<String, List<ExcelImportEntity>> stringListMap = ExcelUtils.readFileManySheet(multipartFile, ExcelImportEntity.class);
        List<MultipartFile> objects = new CopyOnWriteArrayList<>();
        List<ExcelImportEntity> objects1 = new CopyOnWriteArrayList<>();
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        for (Map.Entry<String, List<ExcelImportEntity>> stringListEntry : stringListMap.entrySet()) {
            List<ExcelImportEntity> value = stringListEntry.getValue();
            for (ExcelImportEntity excelImportEntity : value) {
                String address = excelImportEntity.getAddress();
                File file = new File(address);
                if (file.exists()) {
                    CompletableFuture.runAsync(() -> {
                        System.out.println(Thread.currentThread());
                        try {
                            MultipartFile convert = convert(file);
                            objects.add(convert);
                            objects1.add(excelImportEntity);
//                            doHttp(file);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }, executorService);
                }
            }
        }
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(objects1);
        doHttp1(objects,s);
        // 关闭线程池，不再接受新任务，等待所有任务完成
        executorService.shutdown();
        try {
            // 等待线程池关闭，参数为超时时间和时间单位
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                // 若超时，则强制关闭所有正在执行的任务
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            // 若等待时被中断，强制关闭所有正在执行的任务
            executorService.shutdownNow();
            Thread.currentThread().interrupt(); // 重新设置中断标记
        }
    }

    private void doHttp(File file) {
        String url = "http://localhost:8001/importKnowledgeByExcel";//服务端要调用的外部接口
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("multipartFile", file, ContentType.parse("multipart/form-data"), file.getName());
            builder.addTextBody("name","张三",ContentType.TEXT_PLAIN.withCharset("UTF-8"));
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println(response.getStatusLine());
                HttpEntity responseEntity = response.getEntity();
                EntityUtils.consume(responseEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void doHttp1(List<MultipartFile> multipartFiles,String body) {
        String url = "http://localhost:8001/importKnowledgeByExcel1";//服务端要调用的外部接口
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
            MultipartFile multipartFile = null;
            String fileName = null;
            for (int i = 0; i < multipartFiles.size(); i++) {
                multipartFile = multipartFiles.get(i);
                fileName = multipartFile.getOriginalFilename();
                InputStream inputStream = null;
                try {
                    inputStream = multipartFile.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                builder.addBinaryBody("file",inputStream, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            }
            //决中文乱码
            ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, Consts.UTF_8);
            builder.addTextBody("paramStr", body, contentType);
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity responseEntity = response.getEntity();
                EntityUtils.consume(responseEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @PostMapping("/importKnowledgeByExcel")
    public void importKnowledgeByExcel(ExcelImportEntity knowledgeExcelImportParam) throws Exception {
        System.out.println(knowledgeExcelImportParam.getName());
        MultipartFile multipartFile = knowledgeExcelImportParam.getMultipartFile();
        excelImport(multipartFile);
    }
    @PostMapping("/importKnowledgeByExcel1")
    public void importKnowledgeByExcel(@RequestParam(value = "file") List<MultipartFile> mulFiles,@RequestParam(value = "paramStr") String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        List<ExcelImportEntity> entities = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, ExcelImportEntity.class));
        for (int i = 0; i < mulFiles.size(); i++) {
            ExcelImportEntity excelImportEntity = entities.get(i);
            System.out.println(excelImportEntity);
            MultipartFile multipartFile = mulFiles.get(i);
            excelImport(multipartFile);
        }
    }


    /**
     * 解析excel数据为JSONArray
     *
     * @param multipartFile
     * @throws Exception
     */
    @PostMapping("/excelImport")
    public static void excelImport(@RequestPart("multipartFile") MultipartFile multipartFile) throws Exception {
        JSONArray objects = ExcelUtils.readMultipartFile(multipartFile);
        System.out.println("excelImport ======= " + objects);
    }

    /**
     * 解析excel数据为对象
     *
     * @param multipartFile
     * @throws Exception
     */
    @PostMapping("/excelImportToObject")
    public static void excelImportToObject(@RequestPart("multipartFile") MultipartFile multipartFile) throws Exception {
        List<ExcelImportEntity> objects = ExcelUtils.readMultipartFile(multipartFile, ExcelImportEntity.class);
        System.out.println(objects);
    }

    /**
     * 解析excel数据为对象 多个sheet页
     *
     * @param multipartFile
     * @throws Exception
     */
    @PostMapping("/excelImportMuchSheetToObject")
    public void excelImportMuchSheetToObject(@RequestPart("multipartFile") MultipartFile multipartFile) throws Exception {
        excelImport(multipartFile);
    }


    public static MultipartFile convert(File file) throws Exception {
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile(
                "file", // form field name
                file.getName(), // file name
                "multipart/form-data", // content type, can be null or "text/plain" or other depending on the file
                input // file content
        );
        return multipartFile;
    }


    /**
     * 解析excel数据为对象 多个sheet页
     *
     * @param response
     * @throws Exception
     */
    @GetMapping("/excelExport")
    public void excelExport(HttpServletResponse response) {
        // 表头数据
        List<Object> head = Arrays.asList("姓名", "年龄", "性别");
        // 用户1
        List<Object> user1 = new ArrayList<>();
        user1.add("张三");
        user1.add(60);
        user1.add("男");
        // 用户2
        List<Object> user2 = new ArrayList<>();
        user2.add("李四");
        user2.add(28);
        user2.add("女");
        // 将数据汇总
        List<List<Object>> sheetDataList = new ArrayList<>();
        sheetDataList.add(head);
        sheetDataList.add(user1);
        sheetDataList.add(user2);
        ExcelUtils.export(response, "1", sheetDataList);
    }

    @GetMapping("/excelExportDemo")
    public void excelExportDemo(HttpServletResponse response) {
        List<Object> excelImport = new ArrayList<>();
        for (int i = 0; i <= 10; i++) {
            ExcelImportEntity excelImportEntity = new ExcelImportEntity();
            excelImportEntity.setName("张三" + i);
            excelImportEntity.setAge(i);
            excelImportEntity.setDepartment("部门" + i);
            excelImport.add(excelImportEntity);
        }
        Map<String, List<Object>> sheetData = new HashMap<>();
        sheetData.put("demo1", excelImport);
        // 表头数据
        List<Object> head = Arrays.asList("姓名", "年龄", "时间", "部门", "公司");
        ExcelUtils.exportDemo(response, null, "demo", sheetData, new ExcelImportEntity(), head, null);
    }

}
